<template>
  <div class="h100 login">
    <div class="dialog">
      <!-- 验证规则 -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="userName">
          <el-input v-model="ruleForm.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input
            type="password"
            v-model="ruleForm.passWord"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="w100" type="primary" @click="submitForm()"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import axios from '@/http'
export default {
  data() {
    return {
      ruleForm: {
        userName: "",
        passWord: "",
      },
      // 验证规则
      rules: {
        userName: [
          { validator: this.validtorUserName, trigger: "blur" }
        ],
        passWord: [{ validator: this.validtorPassWord, trigger: "blur" }],
      },
    };
  },
  methods: {
    //   验证账号
    validtorUserName(rule, value, next) {
      if (value === "") {
        next(new Error("请输入账号"));
      } else {
          next();
      }
    },
    // 验证密码
    validtorPassWord(rule, value, next) {
      if (value === "") {
        next(new Error("请输入密码"));
      } else {
        next();
      }
    },

    submitForm() {
      this.$refs.ruleForm.validate((flag) => {
        //   flag   所有验证都正确的情况下   true
        if (flag) {
            axios.post('/user/login', this.ruleForm).then(res => {
                sessionStorage.setItem('token', res.token)
                this.$router.push('/home')
            })
        } else {
            this.$message({
                type: "error",
                message: "输入不正确"
            })
        }
      });
    }
  },
};
</script>

<style>
.login {
  background: #09176a;
  position: relative;
}

.dialog {
  position: absolute;
  right: 15%;
  top: 200px;
  width: 400px;
  padding: 60px 20px;
  border-radius: 10px;
  background: #fff;
}
</style>